<template>
  <div class="UserInfo">
    <el-button size="small" type="primary" @click="appendBigLevel">新增大类</el-button>
    <el-row
      :style="{
    'margin-left': '29px',
    'height': '30px',
    'display': 'flex',
    'align-items': 'center'}"
    >
      <el-col :span="4">分类</el-col>
      <el-col :span="4">描述</el-col>
      <el-col :span="3" v-if="isShow">数据来源</el-col>
      <el-col :span="3">数据类型</el-col>
      <el-col :span="2">渠道类型</el-col>
      <el-col :span="3">有效性</el-col>
      <el-col :span="5">操作</el-col>
    </el-row>
    <el-tree
      ref="tree"
      :key="treeKey"
      :data="data"
      node-key="id"
      :expand-on-click-node="false"
      :render-content="renderContent"
      :lazy="true"
      accordion
      :load="loadTreeNode"
      :default-expanded-keys="treeExpandedKeys"
      @node-expand="treeExpand"
      @node-collapse="treeCollapse"
    ></el-tree>
    <BaseDialog
      :visible.sync="isShowDlg"
      :title="dialogTitle"
      destroyOnClose
      width="1050"
      :containerStyle="{height: '100%', overflow: 'auto'}"
    >
      <SourceDetail :type="editType" :rowData="activeData" @close="closeHandler"></SourceDetail>
    </BaseDialog>
  </div>
</template>

<script>
import SourceDetail from './SourceDetail';
import { queryClueSource, removeClueSource } from '@/api/potenCus/basedata/cueSourceDefinition';
import { judgmentBYQueryCondition } from '@/api/potenCus/customer/potenCusManageOEM';
import { dictionary } from '@/utils/dictMixin';
import { notifyAction } from '@/utils';
import { getDataType } from '@/assets/js/auth';
export default {
  name: 'cueSourceDefinition',
  mixins: [dictionary],
  components: {
    SourceDetail
  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'upClueName',
        label: 'label',
        isLeaf: 'leaf'
      },
      activeData: null, // 当前操作数据
      editType: '',
      treeExpandedKeys: [], // 记录打开节点的数组
      treeKey: '', // 控制tree渲染的key
      nodeQuery: {
        name: '' // 编辑树节点表单的model
      },
      isShowDlg: false, // 是否显示编辑节点弹框
      dialogTitle: '', // 浮动窗口名称(新增，编辑)
      dataType: getDataType('dataType'), // 车厂(10461003)、经销商
      isShow: true
    };
  },
  mounted() {},
  methods: {
    // 加载树
    loadTreeNode(node, resolve) {
      const id = node ? node.data.id : '';
      let params = {};
      if (node.level === 0) {
        params = {
          isEnable: 10011003,
          level: 1, // 只有查询一级树有值：1
          upId: '' // 带上当前展开树的id
        };
      } else {
        params = {
          isEnable: 10011003,
          level: '', // 只有查询一级树有值：1
          upId: id // 带上当前展开树的id
        };
      }
      queryClueSource(params).then(res => {
        let treeData = res.data;
        if (res.success && node.level === 0) {
          // 如果是第一次加载数据，直接返回数据
          treeData.forEach(item => {
            item['leaf'] = !item.hasNext;
          });
          resolve(treeData);
        } else if (res.success) {
          // 如果非第一次加载数据，将返回数据拼接到操作节点的childList属性中
          node.data.childList = treeData;
          treeData.forEach(item => {
            item['leaf'] = !item.hasNext;
          });
          resolve(treeData);
        } else {
          resolve([]);
          this.$message({
            type: 'error',
            message: '加载数据出错！'
          });
        }
      });
    },
    // 刷新key值，重新渲染tree
    renderTree() {
      this.treeKey = +new Date();
    },
    init() {
      let params = {
        isEnable: 10011003,
        level: 1, // 只有查询一级树有值：1
        upId: '' // 带上当前展开树的id
      };
      this.queryLevel(params);
    },
    queryLevel(params) {
      queryClueSource(params).then(res => {
        this.data = res.data && res.data.length > 0 ? res.data : [];
        this.data.forEach(item => {
          item.hasNext ? (item.children = [{}]) : '';
        });
      });
    },
    // 新增来源大类
    appendBigLevel() {
      this.editType = 'ADD';
      this.isShowDlg = true;
      this.dialogTitle = '新增来源大类';
      this.activeData = {
        clueLevel: 0, // 无上级来源
        upClueId: null
      };
    },
    // 新增节点
    append(node, data) {
      this.editType = 'ADD';
      this.isShowDlg = true;
      // 记录当前节点数据，供新增弹框关闭后回调用
      this.activeData = data;
      // this.dialogTitle = node.level === 1 ? "新增来源大类" : "新增来源子分类"
      this.dialogTitle = '新增来源子分类';
    },
    // 编辑节点
    modify(node, data) {
      this.nodeQuery.name = data.name;
      // 记录当前操作数据
      this.activeData = data;
      this.editType = 'EDIT';
      this.isShowDlg = true;
      this.dialogTitle = node.level === 1 ? '编辑来源大类' : '编辑来源子分类';
    },
    remove(node, data) {
      let queryCondition = {
        valueType: data.id
      };
      let info = '是否继续删除?';
      this.$confirm(info, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            let params = {
              sourceId: data.id
            };
            removeClueSource(params).then(res => {
              const result = res.data;
              if (result && res.success) {
                // 重新渲染tree
                this.renderTree();
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
      // judgmentBYQueryCondition(queryCondition).then(res => {
      //   console.log(res);
      //   res.data;
      //   let info;
      //   if (true == res.data) {
      //     info = '存在该来源的线索，是否继续删除?';
      //   } else {
      //     info = '是否继续删除?';
      //   }
        
      // });
    },
    renderContent(h, { node, data, store }) {
      let { preDictHandler, dataType } = this;
      // 是否店面数据来源
      let isOwn = false;
      // 是否可操作
      if (dataType.toString() == '10461001') {
        // 店面
        isOwn = data.dataSources == '10451001';
        this.isShow = true;
      } else if (dataType.toString() == '10461003') {
        // 车厂
        isOwn = data.dataSources == '10451002';
        this.isShow = false;
      }
      return (
        // <span class="custom-tree-node">
        <el-row style="width:100%;line-height:200%;" slot-scope="{ node, data }">
          <el-col span={4}>{data.clueName || '_'}</el-col>
          <el-col span={4} style={{'text-overflow': 'ellipsis','overflow': 'hidden'}} title={data.remark || '_'}>{data.remark || '_'}</el-col>
          {this.isShow ? <el-col span={3}>{preDictHandler(data.dataSources, '1045') || '_'}</el-col> : null}
          <el-col span={3}>{preDictHandler(data.dataType, '7026') || '_'}</el-col>
          <el-col span={2}>{preDictHandler(data.channelType, '2589') || '_'}</el-col>
          <el-col span={3}>{preDictHandler(data.isEnable, '1001') || '_'}</el-col>
          <el-col span={5}>
            <div class="grid-content bg-purple-dark">
              <span>
                <el-button size="mini" type="text" disabled={!isOwn} on-click={() => (isOwn ? this.append(node, data) : '')}>
                  新增子分类
                </el-button>
                <el-button size="mini" type="text" disabled={!isOwn} on-click={() => (isOwn ? this.modify(node, data) : '')}>
                  修改
                </el-button>
                <el-button size="mini" type="text" disabled={isOwn && data.leaf ? false : true} on-click={() => (isOwn && data.leaf ? this.remove(node, data) : '')}>
                  删除
                </el-button>
              </span>
            </div>
          </el-col>
        </el-row>
        // </span>
      );
    },
    // 新增节点回调函数
    appendCallback() {
      const data = this.activeData;
      const nodeQuery = this.nodeQuery;
      nodeQuery.parentId = data.id === '0' ? '' : data.id;
    },
    // 编辑节点回调函数
    editCallback() {
      const data = this.activeData,
        nodeQuery = this.nodeQuery;
      data.name = nodeQuery.name;
      // let params= {
      //   "clueLevel": 0,
      //   "clueName": "string",
      //   "dataSources": 0,
      //   "dataType": 0,
      //   "id": 0,
      //   "isEnable": 0,
      //   "ownerCode": "string",
      //   "remark": "string",
      //   "upClueId": 0
      // }
      // 将节点新名称和节点id传递到后台
      // TODO:
      // editClueSource(params).then(res => {
      //   const result = res.data;
      //   if (result && res.success) {
      //     this.$message({
      //       type: "success",
      //       message: "修改成功！"
      //     });
      //     this.renderTree();
      //   }
      // });
    },
    treeExpand(data, node, component) {
      if (!data.leaf) {
        // 不是叶子节点
        this.treeExpandedKeys.push(data.id);
      }
    },
    // 当节点关闭时，移除节点的id
    treeCollapse(data) {
      const index = this.treeExpandedKeys.indexOf(data.id);
      if (index > -1) {
        this.treeExpandedKeys.splice(index, 1);
      }
    },
    // tree node 弹框取消事件
    reset() {
      this.activeData = null;
      this.isShowDlg = false;
      this.nodeQuery = {
        name: '',
        parentId: ''
      };
      this.editType = 'ADD';
    },
    closeHandler(ifShow, ifRender) {
      this.isShowDlg = ifShow;
      if (ifRender) {
        this.renderTree();
      }
    },
    // 字典数据使用前预处理
    preDictHandler(val, code) {
      let resultText = val && String.prototype.includes.call(val, code) ? this.createDictText(val, code) : val;
      return resultText;
    }
  }
};
</script>

<style lang="less">
</style>
